package pers.cz.http;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * 公共请求方法（包含post、get）
 * @program: PostGirl-panent
 * @description: RequestAndResponse
 * @author: Cheng Zhi
 * @create: 2021-03-10 09:17
 **/
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String post(String request, String url, Map<String, String> header) {

        HttpPost post = new HttpPost(url);
        if (header != null && !header.isEmpty()) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        StringEntity entity = new StringEntity(request,"utf-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        // 执行请求
        return post(post);
    }

    /**
     * 通过post请求调用外部接口
     * @param request 请求json字符串
     * @param url 请求地址
     * @return
     */
    public static String getResultByPost(String request, String url) {

        HttpPost post = new HttpPost(url);
        // 设置header部分信息
        post.setHeader("content-type","application/json");
        // 设置入参
        StringEntity entity = new StringEntity(request,"utf-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        // 执行请求
        String result = post(post);

        return result;
    }

    private static String post(HttpPost post) {
        String result = "";
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        try {
            HttpResponse response  = defaultHttpClient.execute(post);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
        } catch (Exception e) {
            logger.error("post请求异常", e);
        }
        return result;
    }
    /**
     * 通过get请求调用外部接口
     * @param request 请求入参
     * @param url 请求地址
     * @return
     */
    public static String getResultByGet(String request, String url) throws URISyntaxException, IOException {

        String result = "";
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求的参数
        url = url + "?" + request;
        URI uri = new URIBuilder(url).build();
        HttpGet get = new HttpGet(uri);
        HttpResponse response = httpclient.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        return result;
    }

    public static void main(String[] args) {
        //getResultByGet(null,"http://localhost:90/queryTestCase/queryAllTestCase");
        String request = "{    \\\"transActionId\\\": 2022061315341201,    \\\"billMonth\\\": 202207,    \\\"acctId\\\": 31099747751,    \\\"userId\\\": 40200104292519,    \\\"phoneId\\\": \\\"13901696022\\\",    \\\"pricingType\\\": 2,    \\\"createDate\\\": 20220613153412,    \\\"inProdList\\\": [        {            \\\"prodId\\\": 2022061315341202,            \\\"offerId\\\": 111000781906,            \\\"offerName\\\": \\\"bbbb\\\",            \\\"billingOfferId\\\": 40500084,            \\\"validDate\\\": 20220613153412,            \\\"expireDate\\\": 20991231000099,            \\\"prodType\\\": 101,            \\\"operType\\\": 1,            \\\"promParamList\\\": [                {                    \\\"paraKey\\\": 0,                    \\\"paraValue\\\": \\\"\\\"                }            ]        },        {            \\\"prodId\\\": 2022061315341203,            \\\"offerId\\\": 111000782069,            \\\"offerName\\\": \\\"cccc\\\",            \\\"billingOfferId\\\": 40500085,            \\\"validDate\\\": 20220613153412,            \\\"expireDate\\\": 20991231000099,            \\\"prodType\\\": 101,            \\\"operType\\\": 1,            \\\"promParamList\\\": [                {                    \\\"paraKey\\\": 0,                    \\\"paraValue\\\": \\\"\\\"                }            ]        }    ]}";
        String url = "http://10.10.152.227:20005/api/queryHttp";
        String resultByPost = getResultByPost(request, url);
        System.out.println(resultByPost);
    }
}
